<template>
  <div class="register">
    <van-nav-bar
      title="注册"
      left-text="返回"
      left-arrow
      @click-left="router.back()"
    />
    
    <div class="register-form">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="formData.username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[
              { required: true, message: '请填写用户名' },
              { pattern: usernamePattern, message: '用户名长度4-20位，只能包含字母、数字和下划线' }
            ]"
          />

          <van-field
            v-model="formData.email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            :rules="[
              { required: true, message: '请填写邮箱' },
              { pattern: emailPattern, message: '请输入正确的邮箱格式' }
            ]"
          />

          <van-field
            v-model="formData.phone"
            name="phone"
            label="手机号"
            placeholder="请输入手机号"
            :rules="[
              { required: true, message: '请填写手机号' },
              { pattern: phonePattern, message: '请输入正确的手机号' }
            ]"
          />
          
          <van-field
            v-model="formData.code"
            center
            clearable
            label="验证码"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请填写验证码' }]"
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                :disabled="counting"
                @click="sendCode"
              >
                {{ counting ? `${counter}s后重发` : '发送验证码' }}
              </van-button>
            </template>
          </van-field>

          <van-field
            v-model="formData.password"
            type="password"
            name="password"
            label="设置密码"
            placeholder="请设置登录密码"
            :rules="[
              { required: true, message: '请设置密码' },
              { pattern: passwordPattern, message: '密码需包含字母和数字，长度6-20位' }
            ]"
          />
          
          <van-field
            v-model="formData.confirmPassword"
            type="password"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入密码"
            :rules="[
              { required: true, message: '请确认密码' },
              { validator: validateConfirmPassword, message: '两次输入的密码不一致' }
            ]"
          />
        </van-cell-group>

        <div class="agreement">
          <van-checkbox v-model="agreed" shape="square">
            我已阅读并同意
            <span class="link" @click.stop="showAgreement">《用户协议》</span>
            和
            <span class="link" @click.stop="showPrivacy">《隐私政策》</span>
          </van-checkbox>
        </div>

        <div class="submit-btn">
          <van-button round block type="primary" native-type="submit">
            注册
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showDialog } from 'vant';
import { register, sendVerifyCode } from '@/api/user';

const router = useRouter();

const formData = ref({
  username: '',
  email: '',
  phone: '',
  code: '',
  password: '',
  confirmPassword: ''
});

const phonePattern = /^1[3-9]\d{9}$/;
const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;
const usernamePattern = /^[a-zA-Z0-9_]{4,20}$/;
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const agreed = ref(false);
const counting = ref(false);
const counter = ref(60);

const validateConfirmPassword = (value) => {
  return value === formData.value.password;
};

const sendCode = async () => {
  if (!phonePattern.test(formData.value.phone)) {
    showToast('请输入正确的手机号');
    return;
  }

  try {
    await sendVerifyCode(formData.value.phone);
    
    counting.value = true;
    counter.value = 60;
    
    const timer = setInterval(() => {
      counter.value--;
      if (counter.value <= 0) {
        clearInterval(timer);
        counting.value = false;
      }
    }, 1000);

    showToast('验证码已发送');
  } catch (error) {
    showToast(error.message || '发送验证码失败');
  }
};

const onSubmit = async (values) => {
  if (!agreed.value) {
    showToast('请先同意用户协议和隐私政策');
    return;
  }

  try {
    await register({
      username: values.username,
      email: values.email,
      phone: values.phone,
      code: values.code,
      password: values.password
    });
    
    showToast({
      type: 'success',
      message: '注册成功',
      onClose: () => {
        router.replace('/login');
      }
    });
  } catch (error) {
    showToast(error.message || '注册失败，请重试');
  }
};

const showAgreement = () => {
  showDialog({
    title: '用户协议',
    message: '用户协议内容...',
    confirmButtonText: '我知道了'
  });
};

const showPrivacy = () => {
  showDialog({
    title: '隐私政策',
    message: '隐私政策内容...',
    confirmButtonText: '我知道了'
  });
};
</script>

<style scoped lang="scss">
.register {
  min-height: 100vh;
  background: #f7f8fa;

  .register-form {
    padding-top: 20px;
  }

  .agreement {
    margin: 16px;
    font-size: 14px;
    
    .link {
      color: #1989fa;
    }
  }

  .submit-btn {
    margin: 16px;
  }
}
</style> 